package br.com.gerenciamento.pg.framework.jpa.model;

import org.eclipse.persistence.mappings.DatabaseMapping;
import org.eclipse.persistence.mappings.converters.Converter;
import org.eclipse.persistence.sessions.Session;


/**
 * 
 * @author wolmirgarbin
 *
 * @param <E>
 */
public abstract class AbstractEnumConverter<E extends EnumConvertable<E, ?>> implements Converter {

	private static final long serialVersionUID = 1L;
	
	private final EnumConvertable<E, ?> convertable;
	
	public AbstractEnumConverter(EnumConvertable<E, ?> convertable) {
		this.convertable = convertable;
	}

	/*
	 * (non-Javadoc)
	 * @see org.eclipse.persistence.mappings.converters.Converter#convertDataValueToObjectValue(java.lang.Object, org.eclipse.persistence.sessions.Session)
	 */
	public Object convertDataValueToObjectValue(Object data, Session session) {
		if (data != null) {
			return convertable.getFromValue(data);
		} else {
			return null;
		}
	}

	/*
	 * (non-Javadoc)
	 * @see org.eclipse.persistence.mappings.converters.Converter#convertObjectValueToDataValue(java.lang.Object, org.eclipse.persistence.sessions.Session)
	 */
	@SuppressWarnings("unchecked")
	public Object convertObjectValueToDataValue(Object data, Session session) {
		if (data instanceof EnumConvertable) {
			return ((EnumConvertable<E, ?>) data).convert();
		}
		return null;
	}

	public void initialize(DatabaseMapping mapping, Session session) {
	}

	public boolean isMutable() {
		return false;
	}
	
}
